package com.Jshop.upload.Service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@Service
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;

    //支持的文件类型
    private static final List<String> CONTENT_TYPES = Arrays.asList(MimeTypeUtils.IMAGE_PNG_VALUE);

    //日志记录器
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    public String upload(MultipartFile file){

        //检查文件类型是否符合要求

        //获得原始文件名
        String originFileName = file.getOriginalFilename();
        //获得文件类型
        String contentType = file.getContentType();

        //文件类型不合法 返回null
        if (!CONTENT_TYPES.contains(contentType)){

            LOGGER.info("文件类型不合法: {}",originFileName);
            return null;
        }


        try {
            //校验文件内容是否合法
            //使用SpringMVC提供的ImageIO 它能帮我们读取或写入图片类型的数据
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null){
                LOGGER.info("文件内容不合法：{}", originFileName);
                return null;
            }

                //保存到服务器
//            file.transferTo(new File("C:\\project\\images\\" + originFileName));


            //获得文件后缀
            String ext = StringUtils.substringAfterLast(originFileName, ".");

            StorePath storePath = this.storageClient.uploadFile
                    (file.getInputStream(), file.getSize(), ext, null);
            //生成url地址并返回
            return "http://image.leyou.com/" + storePath.getFullPath();

        } catch (IOException e) {
            LOGGER.info("服务器内部错误：{}", originFileName);
            e.printStackTrace();
        }

        return null;
    }

}
